package service

import (
	"context"
	"fmt"
	"kubernate-server/conf"
	"net/http"

	"github.com/gin-gonic/gin"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

/**
 * Author: sbw
 * Description: Namespace operation
 * Date:20250927
 */
type NameSpaceService struct {
}

type NamespaceInfo struct {
	Name              string            `json:"name"`
	Status            string            `json:"status"`
	CreationTimestamp metav1.Time       `json:"creationTimestamp"`
	Labels            map[string]string `json:"labels,omitempty"`
	Annotations       map[string]string `json:"annotations,omitempty"`
}

func returnNameSpaceMsg(ctx *gin.Context, msg string, returnCode string) {
	ctx.JSON(http.StatusBadRequest, gin.H{
		"code":   returnCode,
		"messge": msg,
	})
}

func retrunSuccMsg(ctx *gin.Context, msg string) {
	ctx.JSON(http.StatusOK, gin.H{
		"code":   20000,
		"messge": msg,
	})
}

/*
*
创建namespace
*/
func (NameSpaceService) CreateNamespace(ctx *gin.Context) {

	namespace := &corev1.Namespace{
		ObjectMeta: metav1.ObjectMeta{
			Name: ctx.Param("nameSpace"),
		},
	}
	_, err := conf.KuberConfigSet.CoreV1().Namespaces().Create(
		context.TODO(),
		namespace,
		metav1.CreateOptions{},
	)
	if err != nil {
		fmt.Println(err)
		returnNameSpaceMsg(ctx, "创建名称空间失败", "50000")
		return
	}
	retrunSuccMsg(ctx, "创建名称空间成功")
}

/*
*
删除namespace
*/
func (NameSpaceService) DeleteNamespace(ctx *gin.Context) {
	var err = conf.KuberConfigSet.CoreV1().Namespaces().Delete(ctx, ctx.Param("nameSpace"), metav1.DeleteOptions{})
	if err != nil {
		returnNameSpaceMsg(ctx, "删除名称空间失败", "50000")
		return
	}
	retrunSuccMsg(ctx, "删除名称空间成功")
}

/*
*
查询全部namespace
*/
func (NameSpaceService) GetNameSpaceList(ctx *gin.Context) {
	list, err := conf.KuberConfigSet.CoreV1().Namespaces().List(ctx, metav1.ListOptions{})
	if err != nil {
		returnNameSpaceMsg(ctx, "查询名称空间失败", "50000")
		return
	}
	var namespaceInfos []NamespaceInfo
	for _, ns := range list.Items {
		if err != nil {
			returnNameSpaceMsg(ctx, "删除名称空间失败", "50000")
			return
		}

		namespaceInfo := NamespaceInfo{
			Name:              ns.Name,
			Status:            string(ns.Status.Phase),
			CreationTimestamp: ns.CreationTimestamp,
			Labels:            ns.Labels,
			Annotations:       ns.Annotations,
		}
		namespaceInfos = append(namespaceInfos, namespaceInfo)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":          20000,
		"messge":        "success",
		"nameSpaceList": namespaceInfos,
	})
}
